import React, { useState, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { FaUserCircle, FaSignOutAlt, FaCog } from 'react-icons/fa';
import axios from 'axios';
import { toast } from 'react-toastify';

function NavBar() {
  const navigate = useNavigate();
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const timeoutRef = useRef(null);
  
  const handleLogout = () => {
    // 清除本地存储的认证信息
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('isAuthenticated');
    
    // 跳转到指定登录页面
    window.location.href = 'https://my.moshang.site:443/login';
  };

  const handleMouseEnter = () => {
    // 清除已存在的延时器
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    setDropdownVisible(true);
  };

  const handleMouseLeave = () => {
    // 设置延时关闭下拉框
    timeoutRef.current = setTimeout(() => {
      setDropdownVisible(false);
    }, 150); // 150ms延迟
  };

  return (
    <nav className="navbar">
      <div className="navbar-brand">
        <Link to="/">Markdown编辑器</Link>
      </div>
      <div className="navbar-menu">
        <Link to="/docs" className="navbar-item">我的文档</Link>
        <Link to="/shared" className="navbar-item">共享文档</Link>
        <div 
          className="navbar-dropdown"
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
        >
          <button className="navbar-user">
            <FaUserCircle />
            <span>账户</span>
          </button>
          <div className={`dropdown-content ${dropdownVisible ? 'visible' : ''}`}>
            <Link to="/profile" className="dropdown-item">个人资料</Link>
            <Link to="/ai-settings" className="dropdown-item">
              <FaCog /> AI设置
            </Link>
            <button onClick={handleLogout} className="dropdown-item logout-btn">
              <FaSignOutAlt /> 登出
            </button>
          </div>
        </div>
      </div>
    </nav>
  );
}

export default NavBar; 